/**
 * Created by Hexu on 2017/8/22.
 */
var logger = require('../config/log4js');
var ipListService = require('../service/ipListService');
var schedule = require('node-schedule');
var request = require("request");

var jobs = [];

async function startWebData() {

    var proxyList = [];

    var list = await ipListService.queryIPBySize(10000, function (result) {});

    list.forEach(function (ip) {
        proxyList.push(`${ip.ip}:${ip.port}`);
    });

    var rule = new schedule.RecurrenceRule();
    rule.minute = [0, 30];
    var job = schedule.scheduleJob(rule, function () {
        logger.access.info('通过代理来给hvaexlove.com刷流量定时任务: ' + new Date());

        var targetOptions = {
            method: 'GET',
            url: 'http://www.hvaexlove.com/',
            timeout: 8000,
            encoding: null,
        };

        //这里修改一下，变成你要访问的目标网站
        proxyList.forEach(function (proxyurl) {

            console.log(`testing ${proxyurl}`);

            targetOptions.proxy = 'http://' + proxyurl;
            request(targetOptions, function (error, response, body) {
                try {
                    if (error) throw error;


                    body = body.toString();

                    console.log(body);

                    eval(`var ret = ${body}`);


                    if (ret) {
                        console.log(`验证成功==>> ${ret.address}`);
                    }
                } catch (e) {
                    // console.error(e);
                }


            });

        });
    });
    jobs.push(job);
}


module.exports = {
    start : function () {

        startWebData();
        logger.access.info('addWebDataTask Start!');
    },
    stop : function () {
        for (var i = 0; i < jobs.length; i++) {
            jobs[i].cancel();
        }
    }
}